package org.jeecg.modules.demo.soOrderDetail.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.allout.entity.YxAllot;
import org.jeecg.modules.demo.allout.mapper.YxAllotMapper;
import org.jeecg.modules.demo.puInvoice.entity.PuInvoice;
import org.jeecg.modules.demo.puInvoice.mapper.PuInvoiceMapper;
import org.jeecg.modules.demo.soOrderDetail.entity.SoOrderDetail;
import org.jeecg.modules.demo.soOrderDetail.entity.WarehouseOrderVo;
import org.jeecg.modules.demo.soOrderDetail.mapper.SoOrderDetailMapper;
import org.jeecg.modules.demo.soOrderDetail.mapper.WarehouseOrderVoMapper;
import org.jeecg.modules.demo.soOrderDetail.service.ISoOrderDetailService;
import org.jeecg.modules.demo.soQualityOrder.entity.SoQualityOrder;
import org.jeecg.modules.demo.soQualityOrder.mapper.SoQualityOrderMapper;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.mapper.SoSaleOrderMapper;
import org.jeecg.modules.demo.util.generateOddUtilXs;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecg.modules.demo.warehouseorder.entity.WarehouseOrder;
import org.jeecg.modules.demo.warehouseorder.mapper.WarehouseOrderMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: so_order_detail
 * @Author: jeecg-boot
 * @Date: 2021-12-10
 * @Version: V1.0
 */
@Service
public class SoOrderDetailServiceImpl extends ServiceImpl<SoOrderDetailMapper, SoOrderDetail> implements ISoOrderDetailService {

    @Resource
    private SoOrderDetailMapper soOrderDetailMapper;
    @Resource
    private SoQualityOrderMapper soQualityOrderMapper;
    @Resource
    private WarehouseOrderMapper warehouseOrderMapper;
    @Resource
    private YxAllotMapper yxAllotMapper;
    @Resource
    private SoSaleOrderMapper soSaleOrderMapper;
    @Resource
    private PuInvoiceMapper puInvoiceMapper;
    @Resource
    private ISysBaseAPI sysBaseAPI;
    @Resource
    private WarehouseOrderVoMapper warehouseOrderVoMapper;

    private static final String TITLE = "单据审核";

    private String getMsg(String name, String date) {
        String str = "由【" + name + "】于【" + date + "】发起的销售质检单需要您的审核，请及时查看！";
        return str;
    }
    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的销售出库单需要您的审核，请及时查看！";
        return str;
    }
    @Override
    public SoOrderDetail getBySodNumber(String str) {
        return soOrderDetailMapper.getBySodNumber(str);
    }


    @Override
    public List<SoOrderDetail> getByWoNo(String str) {
        return soOrderDetailMapper.getByrkNo(str);
    }


    @Override
    public String getMaxCode() {
        return soOrderDetailMapper.getMaxCode();
    }


    @Override
    @Transactional
    public void delMain(String id) {
        soQualityOrderMapper.deleteByMainId(id);
        soOrderDetailMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            soQualityOrderMapper.deleteByMainId(id.toString());
            soOrderDetailMapper.deleteById(id);
        }
    }

    @Override
    @Transactional
    public boolean unCheckOrder(SoOrderDetail soOrderDetail) {
        try {
            WarehouseOrder warehouseOrder = warehouseOrderMapper.getByDbNo(soOrderDetail.getDbNo());
            warehouseOrderMapper.deleteById(warehouseOrder.getId());
            soOrderDetail.setShName("");
            soOrderDetail.setShTime(null);
            soOrderDetail.setSodStatus(0);
            soOrderDetailMapper.updateById(soOrderDetail);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    public List<SoOrderDetail> getBysoNo(String soNo) {
        return soOrderDetailMapper.getBysoNo(soNo);
    }

    @Override
    @Transactional
    public boolean editRkandOrder(SoOrderDetail soOrderDetail) {
        try {

            ArrayList<String> arr = new ArrayList<String>();
            WarehouseOrder ws = warehouseOrderMapper.getByRkNo(soOrderDetail.getRkNo());//编辑后的入库单
            arr.add(ws.getPoOrder());

            if (soOrderDetail.getBjRkno().equals(soOrderDetail.getRkNo())) {
                ws.setStandingstock(ws.getStandingstock().subtract(soOrderDetail.getXclNum().subtract(soOrderDetail.getBjXcl())));
                warehouseOrderMapper.updateById(ws);

            } else {
                WarehouseOrder bjqws = warehouseOrderMapper.getByRkNo(soOrderDetail.getBjRkno());//修改编辑前的入库单现存量
                bjqws.setStandingstock(bjqws.getStandingstock().add(soOrderDetail.getBjXcl()));
                warehouseOrderMapper.updateById(bjqws);

                ws.setStandingstock(ws.getStandingstock().subtract(soOrderDetail.getXclNum()));
                warehouseOrderMapper.updateById(ws);

                arr.add(bjqws.getPoOrder());
            }

            SoSaleOrder sso = soSaleOrderMapper.getBysoNo(soOrderDetail.getSoOrder());
            sso.setSoLjck(sso.getSoLjck().add(soOrderDetail.getXclNum().subtract(soOrderDetail.getBjXcl())));
            sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
            sso.setIsQuality(0);
            if (sso.getSoKck().compareTo(BigDecimal.valueOf(0)) < 1) { //可出库量<=0时，已出库完
                sso.setIsQuality(1);
            }
            soSaleOrderMapper.updateById(sso);

            for (String po : arr) {

                //采购成本
//            List<WarehouseOrder> rkList = warehouseOrderMapper.getBypoNo(ws.getPoOrder());//根据采购订单号查询所有入库单
                List<WarehouseOrder> rkList = warehouseOrderMapper.getBypoNo(po);//根据采购订单号查询所有入库单
                List<SoOrderDetail> ckList = new ArrayList<>();
                if (rkList.size() > 0) {
                    for (WarehouseOrder who : rkList) {
                        List<SoOrderDetail> sods = soOrderDetailMapper.getByrkNo(who.getWoNo());
                        for (SoOrderDetail ss : sods) {
                            ckList.add(ss);
                        }
                    }
                    Collections.sort(ckList);
//                List<SoOrderDetail> sods = soOrderDetailMapper.getByrkNo(puInvoice.getWoNo());

                    List<PuInvoice> ykp = puInvoiceMapper.getYkpByPoOrder(rkList.get(0).getPoOrder());
                    List<PuInvoice> pt = puInvoiceMapper.getptfpByPoOrder(rkList.get(0).getPoOrder());
//                List<PuInvoice> fp = new ArrayList<>();

                    if (ckList.size() > 0) {
                        if (ykp.size() > 0) {
                            for (PuInvoice s1 : ykp) {
                                s1.setXsFpsl(s1.getFpsl());
                                puInvoiceMapper.updateById(s1);
//                            ykp.add(s1);
                            }
                        }
                        if (pt.size() > 0) {
                            for (PuInvoice pi : pt) {
                                pi.setXsFpsl(pi.getFpsl());
                                puInvoiceMapper.updateById(pi);
                            }
                        }


                        for (SoOrderDetail sd : ckList) {
                            List<PuInvoice> fp = new ArrayList<>();
                            for (PuInvoice s1 : ykp) {
                                fp.add(s1);
                            }

                            WarehouseOrder warehouseOrder = warehouseOrderMapper.getByRkNo(sd.getRkNo());

                            String no = sd.getRkNo().substring(3, 5);
                            List<PuInvoice> p = null;
                            if (!no.equals("RK")) {
                                p = puInvoiceMapper.getBywoNo(warehouseOrder.getPuWoNo());
                            } else {
                                p = puInvoiceMapper.getBywoNo(warehouseOrder.getWoNo());

                            }
                            if (p.size() > 0) {
                                for (PuInvoice pi : p) {
                                    fp.add(pi);
                                }
                            }
//                        WarehouseOrder warehouseOrder = warehouseOrderMapper.getByRkNo(sd.getRkNo());
                            BigDecimal b = sd.getXclNum();
                            BigDecimal s = BigDecimal.valueOf(0.00);
                            if (fp == null) {
                                sd.setCbJine(warehouseOrder.getWsdj().multiply(sd.getXclNum()));
                            } else {

                                for (PuInvoice pi : fp) {
                                    if (b.compareTo(BigDecimal.valueOf(0.00)) == 1) {
                                        //如果销售用开票数量<=出库单实际出库量
                                        if (pi.getXsFpsl().compareTo(b) < 1) {
                                            s = s.add(pi.getWsdj().multiply(pi.getXsFpsl()));
                                            b = b.subtract(pi.getXsFpsl());
                                            pi.setXsFpsl(BigDecimal.valueOf(0.00));
                                            puInvoiceMapper.updateById(pi);
                                        } else {
                                            s = s.add(pi.getWsdj().multiply(b));
                                            pi.setXsFpsl(pi.getXsFpsl().subtract(b));
                                            b = b.subtract(b);
                                            puInvoiceMapper.updateById(pi);
                                        }
                                    }
                                }
                                sd.setCbJine(s.add(b.multiply(warehouseOrder.getWsdj())));
                            }
                            soOrderDetailMapper.updateById(sd);
                        }
                    }
                }
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    public List<WarehouseOrder> getByprdAndWh(WarehouseOrder warehouseOrder) {
        List<WarehouseOrder> list = soOrderDetailMapper.getByprdAndWh(warehouseOrder);
        return list;
    }
//    public IPage<WarehouseOrder> getByprdAndWh(Page<WarehouseOrder> page, String whNum, String prdNo, String chumdwmc) {
//        List<WarehouseOrder> list = soOrderDetailMapper.getByprdAndWh(page, whNum, prdNo, chumdwmc);
//        return page.setRecords(list);
//    }

    @Override
    @Transactional
    public boolean addSoOrderDetail(SoOrderDetail soOrderDetail, SoSaleOrder soSaleOrder, HttpServletRequest req) {
        try {
//            WarehouseOrder warehouseOrder = warehouseOrderMapper.getByRkNo(wo.getWoNo());
            SoOrderDetail sd = new SoOrderDetail();
            sd.setSodQuantity(soSaleOrder.getSoKck());
            sd.setXclNum(soOrderDetail.getXclNum());
            sd.setShName(soOrderDetail.getShName());

            String maxCode = "";
            maxCode = soOrderDetailMapper.getMaxCode();

            Map<String, String> codeMap = new HashMap<>();
            if (maxCode == null) {
                codeMap.put("maxCode", null);
            } else {
                codeMap.put("maxCode", maxCode);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderMapper.getTname(tenantId);
            String xsck = generateOddUtilXs.createCode(codeMap, tname + "CK_");

            String rkno = "";
            String prdLot = "";
            String chengbengongshi = "";
            BigDecimal cb = BigDecimal.valueOf(0.00);
            BigDecimal cb2 = BigDecimal.valueOf(0);
            List<WarehouseOrderVo> whs = soOrderDetail.getWarehouseOrders();


            for (WarehouseOrderVo wh : whs) {
                WarehouseOrder w = warehouseOrderMapper.getByWoNo(wh.getWoNo());
                w.setStandingstock(w.getStandingstock().subtract(wh.getFyje()));
                warehouseOrderMapper.updateById(w);
                WarehouseOrderVo wv = new WarehouseOrderVo();
                wv.setWoNo(wh.getWoNo());
                wv.setSodNo(xsck);
                wv.setFyje(wh.getFyje());
                wv.setPrdBn(wh.getPrdBn());
                wv.setChumdwmc(w.getChumdwmc());
                wv.setCinvname(w.getCinvname());
//                wv.setSoNo(soOrderDetail.getSoOrder());

                //计算采购成本
//                    WarehouseOrder wh = warehouseOrderService.getById(wo.getWoNo());
                List<PuInvoice> fp = new ArrayList<>();
                List<PuInvoice> ykp = puInvoiceMapper.getYkpByPoOrder(w.getPoOrder());
                String no = w.getWoNo().substring(2, 4);//截取入库单号
                List<PuInvoice> ps = null;
                if (!no.equals("RK")) { //根据单号前缀判断是入库单还是其他入库单
                    ps = puInvoiceMapper.getBywoNo(w.getPuWoNo());
                } else {
                    ps = puInvoiceMapper.getBywoNo(w.getWoNo());
                }
                if (ykp.size() > 0) {
                    for (PuInvoice p : ykp) {
                        fp.add(p);
                    }
                }
                if (ps.size() > 0) {
                    for (PuInvoice s1 : ps) {
                        fp.add(s1);
                    }
                }
                BigDecimal b = wh.getFyje();
                BigDecimal s = BigDecimal.valueOf(0.00);
                BigDecimal ss = BigDecimal.valueOf(0.00);
                BigDecimal sd2 = BigDecimal.valueOf(0);
                String chengbgs = "";
                if (fp == null) {
                    ss = w.getWsdj().multiply(b);
                    chengbengongshi = "RK:"+w.getWsdj()+"*"+b;
                } else {

                    for (PuInvoice pi : fp) {
                        if (b.compareTo(BigDecimal.valueOf(0.00)) == 1) {
                            //如果销售用开票数量<=出库单实际出库量
                            if (pi.getXsFpsl().compareTo(b) < 1) {
                                chengbgs = "FP:"+pi.getWsdj()+"*"+pi.getXsFpsl()+"+";
                                s = s.add(pi.getWsdj().multiply(pi.getXsFpsl()));
                                b = b.subtract(pi.getXsFpsl());
                                pi.setXsFpsl(BigDecimal.valueOf(0.00));
                                puInvoiceMapper.updateById(pi);

                            } else {
                                chengbgs = "FP:"+pi.getWsdj()+"*"+b+"+";
                                s = s.add(pi.getWsdj().multiply(b));
                                pi.setXsFpsl(pi.getXsFpsl().subtract(b));
                                b = b.subtract(b);
                                puInvoiceMapper.updateById(pi);

                            }
                        }
                        chengbengongshi = chengbengongshi+chengbgs;
                        System.out.println("chengbengongshi"+chengbengongshi);
                    }

                    if (b.compareTo(BigDecimal.valueOf(0)) == 0){
                        chengbengongshi = chengbengongshi;
                    } else {
                        chengbengongshi = chengbengongshi+"RK:"+w.getWsdj()+"*"+b+"+";
                    }
                    ss = s.add(b.multiply(w.getWsdj()));
                    sd2 = s.add(BigDecimal.valueOf(0));
                }
                wv.setCbje(ss);
                warehouseOrderVoMapper.insert(wv);

                cb = cb.add(ss);
                cb2 = cb2.add(sd2);
                rkno = rkno + wh.getWoNo() + ",";
                prdLot = prdLot + wh.getPrdBn() + ",";
            }
//            BigDecimal d = qqs.subtract(sd.getXclNum());

            sd.setSosCeptNo(chengbengongshi.substring(0, chengbengongshi.length() - 1));
            sd.setCbJine(cb);
            sd.setCbJineTwo(cb2);
            sd.setRkNo(rkno.substring(0, rkno.length() - 1));
            sd.setPrdLot(prdLot.substring(0, prdLot.length() - 1));

            sd.setTradecode(soOrderDetail.getTradecode());
            sd.setSoConNo(soOrderDetail.getSoConNo());
            sd.setSoOrder(soOrderDetail.getSoOrder());
            sd.setSodStatus(soOrderDetail.getSodStatus());
            if (soOrderDetail.getSodDate() == null) {
                sd.setSodDate(new Date());
            } else {
                sd.setSodDate(soOrderDetail.getSodDate());
            }
            sd.setSodNo(xsck);
            sd.setJldw(soSaleOrder.getDanwei());
            sd.setPsTax(soSaleOrder.getPsTax());
            sd.setSoStaff(soSaleOrder.getSoStaff());
            sd.setHsdj(soSaleOrder.getHsdj());
            sd.setHsje(soSaleOrder.getHsje());
            sd.setWsdj(soSaleOrder.getWsdj());
            sd.setWsje(soSaleOrder.getWsje());
            sd.setSl(BigDecimal.valueOf(soSaleOrder.getSl()));
            sd.setIsQuality(0);
            sd.setIsDelete(0);
            sd.setSodStatus(0);
            sd.setDept(soSaleOrder.getDept());

            sd.setTarget(soSaleOrder.getTarget());
            sd.setWhNum(soOrderDetail.getWhNum());
            sd.setPuWhNum(soOrderDetail.getPuWhNum());
            sd.setPrdNo(soSaleOrder.getPrdNo());
            sd.setSoCustom(soSaleOrder.getSoCustom());
            sd.setProject(soSaleOrder.getProject());
            sd.setCkType(soOrderDetail.getCkType());

            sd.setPrice(soOrderDetail.getPrice());

            sd.setYwType(soSaleOrder.getYwType());
            sd.setRemark(soOrderDetail.getRemark());
            sd.setCreateTime(new Date());
            sd.setTzJine(BigDecimal.valueOf(0.00));
            sd.setTzhJine(sd.getCbJine());
            sd.setBjXcl(sd.getXclNum());
//            sd.setBjRkno(wo.getWoNo());
            sd.setBjRkno(sd.getRkNo());
            soOrderDetailMapper.insert(sd);


            SoSaleOrder sso = soSaleOrderMapper.getBysoNo(soSaleOrder.getSoOrder());
            if (sso.getSoLjck() == null) {
                sso.setSoLjck(BigDecimal.valueOf(0));
            }
            sso.setSoLjck(sso.getSoLjck().add(sd.getXclNum()));
            sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
            //累计出库量>=订单总量时
            if (sso.getSoLjck().compareTo(sso.getSoTotail()) > -1) {
                sso.setIsQuality(1);
                sso.setSoKck(BigDecimal.valueOf(0));
            }
            if (sso.getSoKck().compareTo(BigDecimal.valueOf(0)) == 0) {
                sso.setIsQuality(1);
            }
            soSaleOrderMapper.updateById(sso);

//            MessageDTO message = new MessageDTO();
//            message.setFromUser("管理员");
//            message.setToUser(sd.getShName() + ",");
//            message.setTitle(TITLE);
//            message.setContent("销售出库单号为：【" + sd.getSodNo() + "】的订单需要您审核，请及时查看！");
//            message.setCategory("2");
//            sysBaseAPI.sendSysAnnouncement(message);
            LoginUser user = sysBaseAPI.getUserById(sd.getSoStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(sd.getShName()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
            templateParam.put("checkOrder",sd.getSodNo());
            templateParam.put("cd_url","/yunxiao/inventory/SoOrderDetailList");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean addSoQuality(JSONObject jsonObject, HttpServletRequest req) {
        try {
            SoOrderDetail soOrderDetail = JSON.parseObject(jsonObject.toJSONString(), SoOrderDetail.class);
            SoQualityOrder sqo = JSON.parseObject(jsonObject.toJSONString(), SoQualityOrder.class);
            String maxCode = soQualityOrderMapper.getMaxcode();

            Map<String, String> codeMap = new HashMap<>();
            if (maxCode == null) {
                codeMap.put("maxCode", null);
            } else {
                codeMap.put("maxCode", maxCode);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderMapper.getTname(tenantId);
            String xszj = generateOddUtilXs.createCode(codeMap, tname + "ZJ_");

            sqo.setId("");
            sqo.setPuConNo(soOrderDetail.getSoConNo());
            sqo.setSoOrder(soOrderDetail.getSoOrder());
            if (sqo.getQoDate() == null) {
                sqo.setQoDate(new Date());
            }
//            sqo.setSosStaff(soOrderDetail.getSoStaff());
            sqo.setQoNum(xszj);
            sqo.setSodNo(soOrderDetail.getSodNo());
            sqo.setPuConNo(soOrderDetail.getSoConNo());
            sqo.setQoType(1);
            sqo.setCkNum(soOrderDetail.getXclNum());
            sqo.setJldw(soOrderDetail.getJldw());
            sqo.setSl(soOrderDetail.getSl());
            sqo.setQoTax(soOrderDetail.getPsTax());
//        			 sqo.setQoQuantity(0);
            //			 sqo.setQoQuantity(0);
            //			 sqo.setSoStatus(0);
            //			 sqo.setIsDelete(0);
            //			 sqo.setQoCal(0);
            //			 sqo.setQoPic(Double.valueOf(0));
            //			 sqo.setQoTotal(Double.valueOf(0));
            //			 sqo.setQoTaxrate(Double.valueOf(0));
            //			 sqo.setQoTax(Double.valueOf(0));
            //			 sqo.setQoNotax(Double.valueOf(0));
            sqo.setSoStatus(0);
            sqo.setIsDelete(0);
            sqo.setChuku(0);
            sqo.setSoCustom(soOrderDetail.getSoCustom());
//            sqo.setDept(soOrderDetail.getDept());
            sqo.setCreateTime(new Date());
            sqo.setSyNum(sqo.getQoQuantity());
            sqo.setTradecode(sqo.getTradecode());
            soQualityOrderMapper.insert(sqo);
            SoOrderDetail sod = soOrderDetailMapper.selectById(soOrderDetail.getId());
            sod.setIsQuality(1);
            soOrderDetailMapper.updateById(sod);

            //			 SoSaleOrder sso = soSaleOrderService.getBysoNo(sqo.getSoOrder());
            //			 BigDecimal a = sqo.getCkNum().subtract(sqo.getQoQuantity());
            //			 sso.setSoLjck(sso.getSoLjck().subtract(a));
            //			 sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
            //			 if (sso.getSoLjck().compareTo(sso.getSoTotail()) > -1){
            //				 sso.setIsQuality(1);
            //			 } else {
            //				 sso.setIsQuality(0);
            //			 }
            //			 soSaleOrderService.updateById(sso);

            LoginUser user = sysBaseAPI.getUserById(sqo.getSosStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(sqo.getShName() + ",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = simpleDateFormat.format(new Date());
            templateParam.put("ts_date", date);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
            templateParam.put("checkOrder", sqo.getQoNum());
            templateParam.put("cd_url", "/yunxiao/quality/SoSaleOrderList2");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean editRk(SoOrderDetail soOrderDetail) {

        try {
//		 if ("1".equals(soOrderDetail.getIsShjl())) {
            SoSaleOrder sso = soSaleOrderMapper.getBysoNo(soOrderDetail.getSoOrder());
            sso.setSoLjck(sso.getSoLjck().subtract(soOrderDetail.getXclNum()));
            sso.setSoKck(sso.getSoTotail().subtract(sso.getSoLjck()));
//            if (sso.getSoKck().compareTo())
            sso.setIsQuality(0);
            soSaleOrderMapper.updateById(sso);

            String so = soOrderDetail.getRkNo();
            String[] sb = so.split(",");
            BigDecimal cb = BigDecimal.valueOf(0);
            BigDecimal cb2 = BigDecimal.valueOf(0);
            List<SoOrderDetail> ckList = new ArrayList<>();

            for (String rk : sb) {
                WarehouseOrder ws = warehouseOrderMapper.getByRkNo(rk);
                WarehouseOrderVo wh = warehouseOrderVoMapper.getByRknoAndCkno(rk, soOrderDetail.getSodNo());
                ws.setStandingstock(ws.getStandingstock().add(wh.getFyje()));
                warehouseOrderMapper.updateById(ws);

                //成本
                List<WarehouseOrderVo> ckNos = warehouseOrderVoMapper.getcknoByRkno(rk);

                if (ckNos.size() > 0) {
                    for (WarehouseOrderVo ckNo : ckNos) {

//                        if (!ckNo.getSodNo().equals(soOrderDetail.getSodNo())) {

                            SoOrderDetail sd = soOrderDetailMapper.getBySodNumber(ckNo.getSodNo());
                            if (sd != null) {
                                if (!sd.getSodNo().equals(soOrderDetail.getSodNo())) {
                                    ckList.add(sd);
                                }
                                String sod = sd.getRkNo();
                                System.out.println("sodrkno------------------"+sd);
                                String[] sods = sod.split(",");
                                for (String sdd : sods) {
                                    WarehouseOrder w = warehouseOrderMapper.getByWoNo(sdd);

                                    //计算采购成本
//                    WarehouseOrder wh = warehouseOrderService.getById(wo.getWoNo());
                                    List<PuInvoice> ykp = puInvoiceMapper.getYkpByPoOrder(w.getPoOrder());
                                    List<PuInvoice> pt = puInvoiceMapper.getptfpByPoOrder(w.getPoOrder());

                                    if (ykp.size() > 0) {
                                        for (PuInvoice s1 : ykp) {
                                            s1.setXsFpsl(s1.getFpsl());
                                            puInvoiceMapper.updateById(s1);
                                        }
                                    }
                                    if (pt.size() > 0) {
                                        for (PuInvoice pi : pt) {
                                            pi.setXsFpsl(pi.getFpsl());
                                            puInvoiceMapper.updateById(pi);
                                        }
                                    }

                                }
                            }
//                        }
                    }
                }
                warehouseOrderVoMapper.deleteById(wh);
            }
            Collections.sort(ckList);
            if (ckList.size() > 0) {
                for (SoOrderDetail sd : ckList) {
//                    SoOrderDetail sd = soOrderDetailMapper.getBySodNumber(ck.getSodNo());
                    String sork = sd.getRkNo();
                    String[] srk = sork.split(",");
                    for (String rk : srk) {
                        WarehouseOrder w = warehouseOrderMapper.getByWoNo(rk);
                        WarehouseOrderVo wh = warehouseOrderVoMapper.getByRknoAndCkno(rk, sd.getSodNo());

                        //计算采购成本
//                    WarehouseOrder wh = warehouseOrderService.getById(wo.getWoNo());
                        List<PuInvoice> fp = new ArrayList<>();
                        List<PuInvoice> ykp = puInvoiceMapper.getYkpByPoOrder(w.getPoOrder());
                        String no = w.getWoNo().substring(2, 4);
                        List<PuInvoice> ps = null;
                        if (!no.equals("RK")) {
                            ps = puInvoiceMapper.getBywoNo(w.getPuWoNo());
                        } else {
                            ps = puInvoiceMapper.getBywoNo(w.getWoNo());
                        }
                        if (ykp.size() > 0) {
                            for (PuInvoice p : ykp) {
                                fp.add(p);
                            }
                        }
                        if (ps.size() > 0) {
                            for (PuInvoice s1 : ps) {
                                fp.add(s1);
                            }
                        }
                        BigDecimal b = wh.getFyje();
                        BigDecimal s = BigDecimal.valueOf(0);
                        BigDecimal ss = BigDecimal.valueOf(0.00);
                        BigDecimal sd2 = BigDecimal.valueOf(0);
                        if (fp == null) {
                            ss= w.getWsdj().multiply(b);
                        } else {
                            for (PuInvoice pi : fp) {
                                if (b.compareTo(BigDecimal.valueOf(0.00)) == 1) {
                                    //如果销售用开票数量<=出库单实际出库量
                                    if (pi.getXsFpsl().compareTo(b) < 1) {
                                        s = s.add(pi.getWsdj().multiply(pi.getXsFpsl()));
                                        b = b.subtract(pi.getXsFpsl());
                                        pi.setXsFpsl(BigDecimal.valueOf(0.00));
                                        puInvoiceMapper.updateById(pi);
                                    } else {
                                        s = s.add(pi.getWsdj().multiply(b));
                                        pi.setXsFpsl(pi.getXsFpsl().subtract(b));
                                        b = b.subtract(b);
                                        puInvoiceMapper.updateById(pi);
                                    }
                                }
                            }
                            ss = s.add(b.multiply(w.getWsdj()));
                            sd2 = s.add(BigDecimal.valueOf(0));
                        }


                        cb = cb.add(ss);
                        cb2 = cb2.add(sd2);
                    }
                    sd.setCbJine(cb);
                    sd.setCbJineTwo(cb2);
                    soOrderDetailMapper.updateById(sd);
                }
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    @Override
    @Transactional
    public boolean checkOrder(SoOrderDetail soOrderDetail) {
        try {
            warehouseOrderMapper.insert(createWarehouse(soOrderDetail));
            soOrderDetail.setSodStatus(1);
            soOrderDetail.setShTime(new Date());
            //获取登录用户信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            soOrderDetail.setShName(sysUser.getId());
            soOrderDetailMapper.updateById(soOrderDetail);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    public WarehouseOrder createWarehouse(SoOrderDetail soOrderDetail) {
        YxAllot yxAllot = yxAllotMapper.getByDbNo(soOrderDetail.getDbNo());
        WarehouseOrder warehouseOrder = new WarehouseOrder();
        String str = warehouseOrderMapper.getMaxCode();
        Map<String, String> map = new HashMap<>();
        if (str == null) {
            map.put("maxCode", null);
        } else {
            map.put("maxCode", str);
        }
        String name = "QT_";
        String resultCode = generateOddUtil.createCode(map, name);
        warehouseOrder.setPuWoNo(resultCode);
        warehouseOrder.setWoNo(resultCode);
        warehouseOrder.setStandingstock(soOrderDetail.getXclNum());
        warehouseOrder.setFtwsdj(soOrderDetail.getWsdj());
        warehouseOrder.setFtwsje(soOrderDetail.getWsje());
        warehouseOrder.setPuWhNum(yxAllot.getDbNum());
        warehouseOrder.setWhNum(yxAllot.getDbNum());
        warehouseOrder.setQoQuantity(soOrderDetail.getXclNum());
        warehouseOrder.setWoDate(new Date());
        warehouseOrder.setShenhe(0);
        warehouseOrder.setShanchu(0);
        warehouseOrder.setPoTotail(soOrderDetail.getSodQuantity());
        warehouseOrder.setWsdj(soOrderDetail.getWsdj());
        warehouseOrder.setWsje(soOrderDetail.getWsje());
        warehouseOrder.setFttotalcost(soOrderDetail.getWsje());
        warehouseOrder.setMeasureunit(soOrderDetail.getJldw());
        warehouseOrder.setPoStaff(soOrderDetail.getSoStaff());
        warehouseOrder.setDepartment(soOrderDetail.getDept());
        warehouseOrder.setYwlx("9");
        warehouseOrder.setRklb(9);
        warehouseOrder.setCinvname(soOrderDetail.getPrdNo());
        warehouseOrder.setDbNo(soOrderDetail.getDbNo());
        warehouseOrder.setDbsjsl(soOrderDetail.getXclNum());
        Double b = 0.000;
        warehouseOrder.setDbcl(new BigDecimal(b));
        warehouseOrder.setDbce(new BigDecimal(b));
        return warehouseOrder;
    }

    @Override
    public List<SoOrderDetail> getByDbNo(String str) {
        return soOrderDetailMapper.getByDbNo(str);
    }

    @Override
    public SoOrderDetail getBySodNo(String sodNo, String soOrder) {
        return soOrderDetailMapper.getBySodNo(sodNo, soOrder);
    }
}
